import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:video_thumbnail/video_thumbnail.dart';

/// 视频缩略图服务
/// 用于生成和管理视频的缩略图
class VideoThumbnailService {
  /// 缓存目录名
  static const String _thumbnailDir = 'video_thumbnails';

  /// 生成视频缩略图并返回文件路径
  static Future<String?> generateThumbnail(
    String videoPath,
    int videoId,
  ) async {
    try {
      debugPrint('开始为视频生成缩略图，视频路径: $videoPath, 视频ID: $videoId');

      // 获取应用文档目录
      final Directory appDocDir = await getApplicationDocumentsDirectory();

      // 创建缩略图缓存目录
      final Directory thumbnailDir = Directory(
        '${appDocDir.path}/$_thumbnailDir',
      );
      if (!await thumbnailDir.exists()) {
        await thumbnailDir.create(recursive: true);
      }

      // 缩略图文件路径
      final String thumbnailPath = '${thumbnailDir.path}/video_$videoId.jpg';

      // 如果缩略图已存在，直接返回路径
      if (await File(thumbnailPath).exists()) {
        debugPrint('缩略图已存在，直接返回路径: $thumbnailPath');
        return thumbnailPath;
      }

      // 将 asset 文件复制到临时目录
      final tempDir = await getTemporaryDirectory();
      final fileName = videoPath.split('/').last;
      final tempFile = File('${tempDir.path}/$fileName');

      if (!await tempFile.exists()) {
        debugPrint('复制视频文件到临时目录: $videoPath -> ${tempFile.path}');
        final byteData = await rootBundle.load(videoPath);
        await tempFile.writeAsBytes(byteData.buffer.asUint8List());
      }

      debugPrint('开始生成缩略图，临时文件路径: ${tempFile.path}');
      // 使用临时文件生成缩略图
      final String? thumbnail = await VideoThumbnail.thumbnailFile(
        video: tempFile.path,
        thumbnailPath: thumbnailPath,
        imageFormat: ImageFormat.JPEG,
        maxHeight: 512, // 缩略图最大高度
        quality: 100, // 图片质量 (0-100)
      );

      debugPrint('缩略图生成结果: $thumbnail');
      return thumbnail;
    } catch (e, stackTrace) {
      debugPrint('生成视频缩略图失败: $e');
      debugPrint('堆栈跟踪: $stackTrace');
      return null;
    }
  }

  /// 获取缩略图路径（如果不存在则返回null）
  static Future<String?> getThumbnailPath(int videoId) async {
    try {
      final Directory appDocDir = await getApplicationDocumentsDirectory();
      final String thumbnailPath =
          '${appDocDir.path}/$_thumbnailDir/video_$videoId.jpg';

      final File thumbnailFile = File(thumbnailPath);
      if (await thumbnailFile.exists()) {
        return thumbnailPath;
      }
      return null;
    } catch (e) {
      return null;
    }
  }

  /// 删除视频缩略图
  static Future<bool> deleteThumbnail(int videoId) async {
    try {
      final Directory appDocDir = await getApplicationDocumentsDirectory();
      final String thumbnailPath =
          '${appDocDir.path}/$_thumbnailDir/video_$videoId.jpg';

      final File thumbnailFile = File(thumbnailPath);
      if (await thumbnailFile.exists()) {
        await thumbnailFile.delete();
        return true;
      }
      return false;
    } catch (e) {
      return false;
    }
  }

  /// 清除所有缩略图缓存
  static Future<bool> clearAllThumbnails() async {
    try {
      final Directory appDocDir = await getApplicationDocumentsDirectory();
      final Directory thumbnailDir = Directory(
        '${appDocDir.path}/$_thumbnailDir',
      );

      if (await thumbnailDir.exists()) {
        await thumbnailDir.delete(recursive: true);
        return true;
      }
      return false;
    } catch (e) {
      return false;
    }
  }
}
